use std::sync::{Arc, Mutex};
use std::time::Duration;

// 节流函数
fn throttle<F>(interval: Duration, f: F) -> impl FnMut()
where
    F: Fn() + Send + Sync + 'static,
{
    let f = Arc::new(f);
    // 使用 Arc 和 Mutex 共享状态
    let last_time = Arc::new(Mutex::new(None));
    let last_time_clone = Arc::clone(&last_time);

    // 返回一个闭包，用于触发节流函数
    move || {
        let last_time = Arc::clone(&last_time_clone);
        let f = Arc::clone(&f);


        tokio::spawn(async move {
            let f = Arc::clone(&f);
            // 获取当前时间
            let now = tokio::time::Instant::now();

            // 检查是否满足时间间隔
            if let Some(time) = *last_time.lock().unwrap() {
                if now.duration_since(time) < interval {
                    return;
                }
            }

            // 更新上次执行时间并执行函数
            *last_time.lock().unwrap() = Some(now);
            f();
        });
    }
}

#[tokio::main]
async fn main() {
    // 创建一个节流函数，间隔 500ms
    let mut throttled_print = throttle(Duration::from_millis(500), || {
        println!("Throttled: Hello, world!");
    });

    // 模拟高频触发
    for i in 0..10 {
        println!("Trigger: {}", i);
        throttled_print();
        tokio::time::sleep(Duration::from_millis(100)).await;
    }

    // 等待节流函数执行
    tokio::time::sleep(Duration::from_secs(1)).await;
}